﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Text;
using Monk.Site.Assistant;
using System.Web.Caching;
using Newtonsoft.Json;
using Monk.Site.Models;
using Newtonsoft.Json.Linq;

namespace Monk.Site.Assistant
{
    public class FormValidation
    {
        private static CacheDependency ValidationData;

        public static string GetConfigureDirectory()
        {
            return AppDomain.CurrentDomain.BaseDirectory + "Configure/FormValidation.json";
        }

        public static string GetConfigureStr(string jsonDic)
        {
            if (!File.Exists(jsonDic))
            {
                throw new FileNotFoundException("请确保" + jsonDic + "文件存储。");
            }

            return File.ReadAllText(jsonDic);
        }

        public static FormValidationModel GetConfigureObj()
        {
            string jsonDic = GetConfigureDirectory();

            if (HttpContext.Current.Cache[BackendKeys.FormValidation] == null)
            {
                string jsonText = GetConfigureStr(jsonDic);
                FormValidationModel fvModel = JsonConvert.DeserializeObject<FormValidationModel>(jsonText);

                ValidationData = new CacheDependency(jsonDic);
                HttpContext.Current.Cache.Add(BackendKeys.FormValidation, fvModel, ValidationData, DateTime.Now.AddMonths(1), TimeSpan.Zero, CacheItemPriority.Normal, null);
            }

            return HttpContext.Current.Cache[BackendKeys.FormValidation] as FormValidationModel;
        }

        public static Dictionary<string, FieldModel> GetConfigureDicByRoute(string area, string controller, string action)
        {
            Dictionary<string, FieldModel> dic = new Dictionary<string, FieldModel>() { };
            FormValidationModel fvModel = GetConfigureObj();
            ViewModel vm = fvModel.Views.Where(u => u.Area.ToLower() == (area == null ? "" : area.ToString().ToLower()) && u.Controller.ToLower() == controller.ToString().ToLower() && u.Action.ToLower() == action.ToString().ToLower()).FirstOrDefault();
            if (vm != null)
            {
                vm.Fields.ForEach(u =>
                {
                    dic.Add("v_" + u.Field, u);
                });
            }
            return dic;
        }
    }
}